package leetcode.simple._20;

import java.util.Stack;

/**
 * @author mgl
 * @version 1.0
 * @description LeetCode第22题：有效的括号
 * @date 2023/7/6 23:13
 */
public class ValidBracket {
    public boolean isValid(String str) {
        Stack<Character> stack = new Stack<>();
        char[] charArray = str.toCharArray();

        for (char c : charArray) {
            if (c == '(' || c == '[' || c == '{') {
                stack.push(c);
            } else {
                if (stack.isEmpty()) return false;

                if (c == ')') {
                    char temp = stack.pop();

                    if (temp != '(') {
                        return false;
                    }
                } else if (c == ']') {
                    char temp = stack.pop();

                    if (temp != '[') {
                        return false;
                    }
                } else if (c == '}') {
                    char temp = stack.pop();

                    if (temp != '{') {
                        return false;
                    }
                }
            }
        }

        return stack.isEmpty();
    }
}
